# -*- coding:utf-8 -*-
import base64
from flask import Blueprint, request, jsonify, g, make_response
from flask_restful import Resource
from sqlalchemy import func
from time import sleep

from datetime import datetime

from apps.dbConnect.dbCurd import dbCurdD
from apps.ext import db
from apps.model.dbTable import txUsersModel
from comm.constant import UID_

from setting import generate_auth_token, login_required, get_user, openDbBase

user = Blueprint('user', __name__)

class LoginView(Resource):
    # @login_required
    def get(self):

        username = request.args.get('username', None)
        parameters = {}
        if username !='' and username !=None:
            parameters['username'] = username
            data = txUsersModel.query.filter(txUsersModel.username.ilike('%{keyword}%'.format(keyword=username))).all()
        else:
            data = txUsersModel.query.filter().all()
        dataList = []
        for itm in data:
            itmData = itm.to_dict()
            itmData['password'] = base64.b64decode(itm.password).decode('utf-8')
            dataList.append(itmData)
        return make_response(jsonify({'msg':'ok','data':dataList}), 200)
    def post(self):
        # sleep(5)
        args =request.get_json()
        msg = {'msg': '登录成功'}
        if args is None:
            msg['msg'] = '请携带账号和密码'
            return make_response(jsonify(msg), 202)
        username = args.get("username",None)
        password = args.get("password",None)
        if username is None:
            msg['msg'] = '请输入登录账号'
            return make_response(jsonify(msg), 202)
        if password is None:
            msg['msg'] = '请输入登录密码'
            return make_response(jsonify(msg), 202)
        if password == '':
            msg['msg'] = '密码不允许为空'
            return make_response(jsonify(msg), 202)
        # 查询判断用户是否存在
        sql = """
select a.sal_no,b.password,a.name,a.dep from salm a,salm_z b where a.sal_no=b.sal_no and isnull(b.password,'')!='' and a.sal_no=:usr
        """
        # print(sql,username)
        res,err = dbCurdD.dbOneJson(sql,{"usr":username})
        if err!=None:
            msg['msg'] = '登录失败' + err
            return make_response(jsonify(msg), 202)
        if res is None:
            msg['msg'] = '用户不存在'
            return make_response(jsonify(msg), 202)

        if password != res['password']:
            msg['msg'] = '密码错误'
            return make_response(jsonify(msg), 202)

        # 生产token
        tokenData = {}
        tokenData['dep'] = res['dep']
        tokenData['username'] = res['name']
        tokenData['userId'] = username
        token = generate_auth_token(tokenData).decode()
        tokenData['token'] = token
        config = openDbBase()
        tokenData['broadcastName'] = config['BROADCASTNAME']
        tokenData['broadcastactionName'] = config['BROADCASTACTIONNAME']
        return make_response(jsonify(tokenData), 201)
